package aspect;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import pojo.Admin;

@Component
@Aspect
public class DigestAspect {

	private final String pointcut="execution(* service.AdminService.regist(..))";
	private final String pointcut2="execution(* service.AdminService.login(..))";
	private MessageDigest digest;
	
	public DigestAspect() {
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	
	@Around(value=pointcut)
	public Object regist(ProceedingJoinPoint point){
		Object o = null;
		Admin a = (Admin)point.getArgs()[0];  //接收连接点传入的参数
		a.setPassword(process(a.getPassword()));
		try {
			o = point.proceed(new Object[]{a});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	
	@Around(value=pointcut2)
	public Object login(ProceedingJoinPoint point){
		Object o=null;
		String s=(String)point.getArgs()[1];
		String ss=process(s);
		try {
			o=point.proceed(new Object[]{point.getArgs()[0],ss});
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return o;
	}
	
	private String process(String s){
		String ss = null;
		try {
			byte[] bs = digest.digest(s.getBytes("ISO-8859-1"));
			ss = new String(bs,"ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return ss;
	}
}
